package org.herui.campus.service.controller;

import com.mlnx.common.entity.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.shan.spring.base.BaseController;
import org.shan.spring.base.annotations.SysLog;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "主机接口", tags = {"主机接口"})
@SysLog(title = "主机")
@RestController
@RequestMapping(value = "/campus/host")
public class HostController extends BaseController {

    static Map<String, String> nameMap = new HashMap<>();
    static {
        nameMap.put("campus-sys", "系统服务");
        nameMap.put("iot-device-gateway", "设备网关服务");
        nameMap.put("iot-device", "设备服务");
    }

    @Autowired
    DiscoveryClient discoveryClient;

    @ApiOperation(
            value = "获取所有主机",
            notes = ""
    )
    @GetMapping({""})
    public ResponseData<List<HostInfo>> listHost() {

        List<HostInfo> hostInfos = new LinkedList<>();

        List<String> services = discoveryClient.getServices();
        List<List<ServiceInstance>> lists = services.stream().map(s -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(s);
            for (ServiceInstance serviceInstance: instances){
                HostInfo hostInfo = new HostInfo();
                hostInfos.add(hostInfo);
                BeanUtils.copyProperties(serviceInstance, hostInfo);
                hostInfo.setUri(serviceInstance.getUri().toString());
                hostInfo.setName(nameMap.get(serviceInstance.getServiceId()));
            }
            return instances;
        }).collect(Collectors.toList());

        return result(hostInfos);
    }

    @Data
    static class HostInfo {
        private String name;
        private String instanceId;
        private String serviceId;
        private String host;
        private int port;
        private boolean secure;
        private String uri;
        private Map<String, String> metadata;
    }
}
